let submitForm = null;
let questions = [], answers = [];
let jQueryQuestions = {};

$(function () {

  submitForm = $('<form id="submitForm" class="row justify-content-center align-items-start"></form>');
  submitForm.submit(function (event) {
    event.preventDefault();
    let inputList = $(this).find('*').filter(':input');
    let valueList = {};
    inputList.each(function () {
      if ($(this).prop('tagName') !== 'BUTTON') {

        valueList[$(this).attr('name')] = $(this).val();
      }
    })

    //new valueList
    // let dataList = {};
    // dataList.username = $('#username').val();
    // dataList.answers = valueList;

    // submit form data
    $.ajax({
      url: '/answer/add/'+$('#username').val(),
      data: JSON.stringify(valueList),
      contentType: 'application/json',
      method: 'POST',
      success: [function (data, textStatus, jqXHR) {
        if (data.code === 0) {
          toggleComponents();
        }
      }],
      error: [function (jqXHR, textStatus, errorThrown) {
        console.log("submit form data failure");
      }]
    });

  });

  // request questionnaire
  $.ajax({
    url: '/questionnaire/queryLasted',
    contentType: 'application/json',
    method: 'GET',
    success: [function (data, textStatus, jqXHR) {
      console.log(data);
      // create Jquery Objects of questions
      createJQueryObject(data.data.questions);

      // request the past questionnaire done
      $.ajax({
        url: '/answer/'+$('#username').val(),
        contentType: 'application/json',
        method: 'GET',
        success: [function (data, textStatus, jqXHR) {
          console.log(data);
          // draw the html
          jsonToHtml(data.data.answers);
          // close the button if questions are doned today
          if (data !== null && data.data.isFinish === true) {
            toggleComponents();
          }
        }],
        error: [function (jqXHR, textStatus, errorThrown) {
          console.log("request the past questionnaire done failure");
        }]
      });
    }],
    error: [function (jqXHR, textStatus, errorThrown) {
      console.log("request questionnaire failure");
    }]
  });

});




function createJQueryObject(questionnairePrototype) {
  let keys = Object.getOwnPropertyNames(questionnairePrototype);

  for (let i = 0; i < keys.length; i++) {
    //'1', '1-1-1'等为问题, '1-1', '1-1-1-1'等为答案
    if (keys[i].length % 4 === 3) {
      answers.push(keys[i]);
    } else {
      questions.push(keys[i]);
    }
  }

  questions.sort();
  answers.sort();

  for (let i = 0; i < questions.length; i++) {
    let re = new RegExp(`^${questions[i]}-\\d$`);
    let ans = answers.filter(e => re.test(e));
    if (ans.length === 0) {
      //使用模板字符串，元素之间换行会多出一个文本结点
      jQueryQuestions[questions[i]] = $(`<label for=${questions[i]} class='form-label'>${questionnairePrototype[questions[i]]}: </label><input id=${questions[i]} class='form-control' type='text' name=${questions[i]} required/>`);

    } else {
      let options = `<option value=''>请选择答案</option>`;
      for (let j = 0; j < ans.length; j++) {
        options = options + `<option value=${ans[j]}>${questionnairePrototype[ans[j]]}</option>`;
      }
      //使用模板字符串，元素之间换行会多出一个文本结点
      jQueryQuestions[questions[i]] = $(`<label for=${questions[i]} class='form-label'>${questionnairePrototype[questions[i]]}: </label><select name=${questions[i]} class='form-select' id=${questions[i]} required/>${options}</select> `);
      jQueryQuestions[questions[i]].eq(1).change(onSelectedChange);
    }
  }

}

//渲染问卷
function jsonToHtml(oldQuestionnaire) {

  // 判断是否有上一次的提交记录，有就回显，没有就渲染空白问卷
  if (oldQuestionnaire === null) {

    // questions.length[i] === 1 是为了只渲染第一层的问题
    for (let i = 0; i < questions.length; i++) {
      if (questions[i].length === 1) {
        submitForm.append($(`<div class='col-sm-7 mb-3'></div>`).append(jQueryQuestions[questions[i]]));
      }

    }
  } else {
    for (let i = 0; i < questions.length; i++) {
      if (oldQuestionnaire[questions[i]]) {
        let hasAnsQuestion = jQueryQuestions[questions[i]].val(oldQuestionnaire[questions[i]]);
        submitForm.append($(`<div class='col-sm-7 mb-3'></div>`).append(hasAnsQuestion));
      }

    }
  }

  submitForm.append($(
      `<div class="col-sm-7 mb-3 d-flex justify-content-center">
    <button id='submitButton' type="submit" class="w-75 btn btn-outline-primary btn-lg">提交</button>
  </div>`
  ));
  $('div.container').append(submitForm);

  // set Date
  let date = new Date();
  $('#date').val(`${date.getMonth() + 1}月${date.getDate()}日`);
}

function onSelectedChange(e) {
  let parent = $(e.target).closest('div').first();
  let val = $(e.target).val() === '' ? $(e.target).attr('name') : $(e.target).val();


  //detach subquestions
  for (let remain = parent.next(); remain.length !== 0; remain = parent.next()) {
    let select = remain.find('select');
    let input = remain.find('input');
    let nextQuestionName = '';
    if (select.length !== 0) {
      nextQuestionName = select.attr('name');
    } else if (input.length !== 0) {
      nextQuestionName = input.attr('name');
    } else {
      break;
    }
    if (nextQuestionName.length > val.length) {
      jQueryQuestions[nextQuestionName] = remain.children();
      remain.remove();
    } else {
      break;
    }
  }

  // insert subquestions
  let re = new RegExp(`^${val}-\\d$`);
  let subquestions = questions.filter((e) => re.test(e));
  if (subquestions.length !== 0) {
    // 使用<li>存在编号问题
    parent.after(subquestions.map((e) => $(`<div class='col-sm-7 mb-3'></div>`).append(jQueryQuestions[e])));
  }

}


function toggleComponents() {
  $('#submitButton').toggleClass('d-none');
  $('#tipsToDo').toggleClass('d-none');
  $('#tipsDone').toggleClass('d-none');
}
// function reappearAnswers(oldQuestionnaire) {
//   let inputList = submitForm.find('*').filter(':input');
//   inputList.each(function () {
//     if ($(this).prop('tagName') !== 'BUTTON') {
//       $(this).val(oldQuestionnaire[$(this).attr('name')]);
//       if ($(this).prop('tagName') === 'SELECT') {
//         $(this).change();
//       }
//     }
//   })
//   if (oldQuestionnaire.date === true) {
//     $('submitButton').addClass('d-none');
//   }
// }